package tech.bmatch.meituan.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.bmatch.meituan.model.Merchant;
import tech.bmatch.meituan.service.MerchantService;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @program: S1P1FinalProject
 * @description: 数据可持续
 * @author: Awake
 * @create: 2018-10-03 10:33
 **/
public abstract class MerchantFileStoreServiceImpl implements MerchantService {
    public static final Logger logger = LoggerFactory.getLogger(MerchantFileStoreServiceImpl.class);

    private static ObjectMapper objectMapper = new ObjectMapper();
    private static File file = new File("./demo.json");

    @Override
    public void init() {
        if (!file.exists()) {
            return;
        }

        try {
            List<Merchant> merchantList = objectMapper.readValue(file, new TypeReference<List<Merchant>>() {
            });
            for (Merchant merchant : merchantList) {
                addMerchant(merchant);
            }
        } catch (IOException e) {
            logger.error("", e);
        }
    }

    public void store(List<Merchant> merchants) {
        if (merchants == null) {
            return;
        }
        try {
            objectMapper.writeValue(file, merchants);
        } catch (IOException e) {
            logger.error("", e);
        }
    }

}

